#pragma once
#include <iostream>
#include <string>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <cstring>

class InetAddr
{
public:
    // 网络系列转主机系列
    InetAddr(struct sockaddr_in &addr)
        : _addr(addr)
    {
        _port = ntohs(_addr.sin_port);
        //_ip = inet_ntoa(_addr.sin_addr);
        char buffer[64];
        inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(buffer));
        _ip=buffer;
    }

    // 主机系列转网络系列
    InetAddr(const std::string ip, int port)
        : _ip(ip),
          _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
    }

    uint16_t Port()
    {
        return _port;
    }

    std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }

    const struct sockaddr_in &GetAddr()
    {
        return _addr;
    }

    bool operator==(InetAddr &peer)
    {
        return _ip == peer._ip && _port == peer._port;
    }

private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};